
<template>
  <div class="search-box">
    <div class="search">
      <form action
            v-on:submit.prevent>
        <i @click="search">
          <!-- TODO svg替换 -->
          <!-- <svg-icon icon-class="icon_search" /> -->
          <img class="img_search" src="https://img.wifenxiao.com/h5-wfx/images/common/search-icon.png" />
        </i>
        <input ref="query"
               type="search"
               @confirm="search"
               v-model.trim="query"
               class="box"
               :placeholder="placeholder" />
      </form>
    </div>
    <!-- <button v-show="showBtn" class="searchBtn" @click="search">搜索</button> -->
  </div>
</template>

<script>
import Vue from 'vue'
/**
 * 通过v-model / @query / @search 三种方法向外抛出参数
 * @query 为节流方法
 */
export default Vue.extend({
  props: {
    placeholder: {
      type: String,
      default: '搜索关键字'
    },
    showBtn: {
      type: Boolean,
      default: false
    },
    value: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      query: this.value
    }
  },
  methods: {
    clear() {
      this.query = ''
    },
    blur() {
      this.$refs.query.blur()
    },
    debounce(func, delay) {
      let timer
      return function(...args) {
        if (timer) {
          clearTimeout(timer)
        }
        timer = setTimeout(() => {
          func.apply(this, args)
        }, delay)
      }
    },
    search() {
      this.$emit('search', this.query)
    }
  },
  watch: {
    value(newVal) {
      this.query = newVal
    },
    query(newVal) {
      this.$emit('input', newVal)
    }
  },
  created() {
    this.$watch(
      'query',
      this.debounce(newQuery => {
        this.$emit('query', newQuery)
      }, 300)
    )
  }
})
</script>

<style lang="scss">
@import "src/styles/variables.scss";
.search-box {
  box-sizing: border-box;
  width: 100%;
  background: $default;
  // border-radius: 20px;
  padding: 10px 0;
  display: flex;
  justify-content: center;
  align-content: center;
  .search {
    flex: 1;
    display: flex;
    align-items: center;
    padding: 0 25px;
    // width: 98%;
    height: 72px;
    border-radius: 37px;
    background-color: #f7f7f7;
    box-sizing: border-box;
    form {
      flex: 1;
      display: flex;
      align-items: center;
      .svg-icon {
        font-size: 28px;
        color: #999;
      }
      .img_search{
        width: 28px;
        height: 28px;
      }
      .box {
        flex: 1;
        margin: 0 10px;
        height: 72px;
        padding: 15px 0;
        background: #f7f7f7;
        color: #999999;
        font-size: 24px;
        border: none;
        outline: none;
        &::placeholder {
          color: #999;
          line-height: 1.3;
        }
      }
    }
  }
  .searchBtn {
    width: 160px;
    font-size: 28px;
    border: none;
    outline: none;
    height: 75px;
    margin-left: 20px;
    border-radius: 37px;
    background-color: $mainColor;
    color: $default;
  }
}
</style>